package classtrain;

import java.io.*;
import java.net.URL;
import java.util.ArrayList;

/**
 * @DESCRIPATION
 * @AUTHOR 戴超
 * @DATE 2018/6/19
 **/
public class GetImageTest {
    public static void main(String[] args) throws Exception {
        URL url = new URL("http", "jwc.jxau.edu.cn",
                80, "");
        InputStream input = url.openStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(input));
        String str = null;
        while ((str = bufferedReader.readLine()) != null) {
            System.out.println(str);
            if (str.contains("<img")) {
                ArrayList<String> imgUrl = getImgUrl(str);
                for (String s : imgUrl) {
                    writeFile(s);
                }
            }
        }
        input.close();
        bufferedReader.close();
    }

    private static void writeFile(String s) throws Exception {
        if (!s.contains("http") || s.contains("https")) {
            s = "http:" + s;
        }
        InputStream inputStream = new URL(s).openStream();
        String fileName = getFileName(s);
//        System.out.println(fileName);
        writeFile(fileName, inputStream);
    }

    private static void writeFile(String fileName, InputStream input) throws Exception {
        File file = new File(fileName);
        file.getParentFile().mkdirs();
        FileOutputStream out = new FileOutputStream(fileName);
        byte[] bytes = new byte[1024];
        int index;
        while ((index = input.read(bytes)) != -1) {
            out.write(bytes, 0, index);
            out.flush();
        }
        out.close();
        input.close();
    }

    private static String getFileName(String s) {
        StringBuilder sb = new StringBuilder();
        sb.append("./jxau/");
        sb.append(System.currentTimeMillis());
        sb.append(".jpg");

        return sb.toString();
    }

    private static ArrayList<String> getImgUrl(String str) {
        ArrayList<String> strings = new ArrayList<>();
        String[] split = str.split("<img");
        for (int i = 1; i < split.length; i++) {
            String s = split[i];
            String substring = s.substring(s.indexOf("src=") + 5);
            substring = substring.substring(0, substring.indexOf("\"")).trim();
            if (substring != null && substring.length() > 0) {
                strings.add(substring);
            }
        }
        return strings;
    }
}
